package cn.getech.data.development.controller;


import cn.getech.data.development.constant.DataDevelopmentBizExceptionEnum;
import cn.getech.data.development.constant.VersionType;
import cn.getech.data.development.dto.IdAndNameDto;
import cn.getech.data.development.model.dto.BdpAddVersionDto;
import cn.getech.data.development.model.dto.ProcRelDto;
import cn.getech.data.development.model.dto.ProcRelStrDto;
import cn.getech.data.development.model.qo.BdpVersionQO;
import cn.getech.data.development.model.vo.BdpAddVersionVO;
import cn.getech.data.development.model.vo.BdpVersionVO;
import cn.getech.data.development.service.IBdpVersionService;
import cn.getech.data.intelligence.common.exception.RRException;
import cn.getech.data.intelligence.common.utils.PageUtils;
import cn.getech.data.intelligence.common.utils.PojoUtils;
import cn.getech.data.intelligence.common.utils.R;
import cn.getech.system.center.annotation.SysLog;
import cn.getech.system.center.constant.OperationModulesEnum;
import cn.getech.system.center.constant.OperationTypeEnum;
import cn.getech.system.center.constant.module.ModuleEnum;
import cn.getech.system.center.entity.SysUserEntity;
import cn.getech.system.center.service.SysUserService;
import cn.getech.system.center.utils.ShiroUtils;
import cn.hutool.core.collection.CollectionUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 打包的版本 前端控制器
 * </p>
 *
 * @author hujz
 * @since 2020-06-30
 */
@RestController
@RequestMapping("/bdp/version")
public class VersionController {

    @Autowired
    private IBdpVersionService iBdpVersionService;
    @Autowired
    private SysUserService sysUserService;

    @ApiOperation(value = "分页查询版本管理列表")
    @PostMapping("/page")
    @SysLog(value="分页查询版本管理列表",type= OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions(value = {"bdp:version:page","bdp:procInfo:manage"},logical=Logical.OR)
    public R page(@RequestBody BdpVersionQO versionQO) {
        versionQO.setUserId(ShiroUtils.getUserId());
        versionQO.setTenantId(ShiroUtils.getTenantId());
        PageUtils page = iBdpVersionService.page(versionQO);
        if (null != page) {
            List<BdpVersionVO> bdpVersionVOS = PojoUtils.listConvert(BdpVersionVO.class, page.getList());
            if (CollectionUtil.isNotEmpty(bdpVersionVOS)) {
                filledData(bdpVersionVOS,ShiroUtils.getUserId());
            }
            page.setList(bdpVersionVOS);
            return R.okWithPage(page);
        }
        return R.okWithPage(null);
    }

    private void filledData(List<BdpVersionVO> bdpVersionVOS, Long userId) {
        if(CollectionUtil.isEmpty(bdpVersionVOS)){
            return;
        }
        Set<Integer> createPerIds = bdpVersionVOS.stream().map(BdpVersionVO :: getCreatePer).collect(Collectors.toSet());
        //查询用户
        if(CollectionUtil.isNotEmpty(createPerIds)){
            List<Long> lists = new ArrayList<>();
            createPerIds.forEach(o -> {
                lists.add(Long.valueOf(o));
            });
            List<SysUserEntity> users = sysUserService.getUsers(lists);
            if(CollectionUtil.isNotEmpty(users)){
                for (BdpVersionVO bdpVersionVO : bdpVersionVOS) {
                    SysUserEntity sysUserEntity = users.stream().filter(o -> Objects.equals(o.getUserId().intValue(), bdpVersionVO.getCreatePer())).findAny().orElse(null);
                    if(null != sysUserEntity){
                        bdpVersionVO.setCreatePerName(sysUserEntity.getUsername());
                    }
                }
            }
        }
        //是否可以下载 ： 自己创建的和版本包中选择的项目对应的项目创建者（即项目管理员）可以下载
        Set<Integer> createPers = new HashSet<>();
        for (BdpVersionVO bdpVersionVO : bdpVersionVOS) {
            createPers.add(bdpVersionVO.getCreatePer());
            createPers.add(bdpVersionVO.getCreateProcPer());
            if(createPers.contains(userId.intValue())){
                bdpVersionVO.setIsDownload(1);
            }
            createPers.clear();
        }

    }

    @ApiOperation(value = "删除版本")
    @PostMapping("/delete/{id}")
    @SysLog(value="删除版本",type= OperationTypeEnum.DELETECODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:version:delete"})
    public R delete(@PathVariable("id") Long id) {
        iBdpVersionService.deleteById(id);
        return R.ok();
    }


    @ApiOperation(value = "新增版本")
    @PostMapping("/add")
    @SysLog(value="新增版本",type= OperationTypeEnum.ADDCODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:version:add"})
    public R add(@RequestBody BdpAddVersionVO bdpAddVersionVO) {
        Assert.notNull(bdpAddVersionVO, DataDevelopmentBizExceptionEnum.PARAM_ERROR.getMessage());
        bdpAddVersionVO.setVersionType(VersionType.PACK.getCode());
        bdpAddVersionVO.setCreatePer(ShiroUtils.getUserId().intValue());
        BdpAddVersionDto bdpAddVersionDto = new BdpAddVersionDto();
        BeanUtils.copyProperties(bdpAddVersionVO, bdpAddVersionDto);
        //版本包 不能为空
        if(CollectionUtil.isEmpty(bdpAddVersionVO.getConnectList())
                && CollectionUtil.isEmpty(bdpAddVersionVO.getWorkMenuList())
                && CollectionUtil.isEmpty(bdpAddVersionVO.getRealTableList())
                && CollectionUtil.isEmpty(bdpAddVersionVO.getRealWorkMenuList())
                && CollectionUtil.isEmpty(bdpAddVersionVO.getTableList())){
            throw new RRException("版本包文件内容不能为空！");
        }
        bdpAddVersionDto.setConnectList(PojoUtils.listConvert(IdAndNameDto.class, bdpAddVersionVO.getConnectList()));
        bdpAddVersionDto.setUdfList(PojoUtils.listConvert(IdAndNameDto.class, bdpAddVersionVO.getUdfList()));
        bdpAddVersionDto.setWorkMenuList(PojoUtils.listConvert(IdAndNameDto.class, bdpAddVersionVO.getWorkMenuList()));
        bdpAddVersionDto.setTableList(PojoUtils.listConvert(IdAndNameDto.class, bdpAddVersionVO.getTableList()));
        bdpAddVersionDto.setNotCheackWorkMenuList(PojoUtils.listConvert(IdAndNameDto.class, bdpAddVersionVO.getNotCheackWorkMenuList()));
        iBdpVersionService.add(bdpAddVersionDto);
        return R.ok();
    }


    @ApiOperation(value = "查看版本")
    @GetMapping("/view/{id}")
    @SysLog(value="查看版本",type= OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:version:page"})
    public R view(@PathVariable("id") Long id) {
        BdpAddVersionDto bdpAddVersionDto = iBdpVersionService.view(id);
        return R.okWithData(bdpAddVersionDto);
    }


    @ApiOperation(value = "根据项目查询到关联了这个项目的数据源、仓库、作业流、udf函数")
    @GetMapping("/resourceList/{procId}")
    @SysLog(value="根据项目查询到关联了这个项目的数据",type= OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    public R resourceList(@PathVariable("procId") Long procId) {
        ProcRelDto procRelDto = iBdpVersionService.resourceList(procId);
        return R.okWithData(procRelDto);
    }

    @ApiOperation(value = "查询历史版本的关联了这个项目的数据源、仓库、作业流、udf函数")
    @GetMapping("/olderresourceList/{versionId}")
    @SysLog(value="根据项目查询历史版本的这个项目的数据",type= OperationTypeEnum.SELECTCODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    public R olderresourceList(@PathVariable("versionId") Long versionId) {
        ProcRelStrDto procRelStrDto = iBdpVersionService.olderresourceList(versionId);
        return R.okWithData(procRelStrDto);
    }


    @ApiOperation("下载版本")
    @GetMapping("/downloadVersion")
    @SysLog(value="下载版本",type= OperationTypeEnum.DOWNLOADCODE, modulesType = OperationModulesEnum.SYSMODECODE,platformModuleType = ModuleEnum.OPERATION_CENTER_MODULE_CODE)
    //todo 0925
    //@RequiresPermissions({"bdp:version:downloadVersion"})
    public void downloadVersion(@RequestParam Long versionId, HttpServletResponse response, HttpServletRequest request) throws Exception {
        if (null == versionId) {
            throw new RRException("版本id不能为空！");
        }
        iBdpVersionService.downZipVersion(versionId, response,request);
    }

}

